<?php

namespace Modules\User\Models;


use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\MustVerifyEmail;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Support\Facades\Hash;

/**
 * 基础用户模型
 * @author long2ge
 * @date 2023/10/26 5:16 PM
 * @class AdminUser
 * @package Modules\User\Models
 * @describe
 */
abstract class BaseUser extends BaseModel implements
    AuthenticatableContract,
    AuthorizableContract,
    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword, MustVerifyEmail;
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * 根据用户名字获取密码
     * User: long
     * Date: 2019/4/7 6:22 PM
     * Describe:
     * @param $username
     * @return mixed
     */
    public function findForPassport($username)
    {
        return (new static())->where('username', $username)->first();
    }

    /**
     * 退出登陆
     * User: long
     * Date: 2020/5/3 5:33 PM
     * Describe:
     * @throws \Exception
     */
    public function logout()
    {
        $token = $this->token();

        $token->delete();
    }

    /**
     * 加密密码
     * User: long
     * Date: 2021/4/8 12:02 上午
     * Describe:
     * @param string $password
     * @return string
     */
    public static function encryptPassword(string $password)
    {
        return Hash::make($password);
    }

    /**
     * 根据账号密码注册
     * User: long
     * Date: 2021/4/8 12:12 上午
     * Describe:
     * @param $username
     * @param $password
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model
     */
    public static function registerByPassword($username, $password)
    {
        return static::query()->create([
            'username' => $username,
            'password' => self::encryptPassword($password),
        ]);
    }

    /**
     * passport 密码验证方法
     * User: long
     * Date: 2019/9/7 2:26 AM
     * Describe:
     * @param string $password 验证密码方法
     * @return bool
     */
    public function validateForPassportPasswordGrant($password)
    {
        return $password == $this->password;
    }

}
